import { playModeMap } from '@/common/config'

// 当前歌曲在播放列表中的索引
export const currentIndex = (state) => {
  return state.playlist.findIndex(({ id }) => id === state.currentSong.id)
}

// 下一首歌
export const nextSong = (state, getters) => {
  return getIndexByOperation(state, getters, 'next');
}

// 上一首歌
export const prevSong = (state, getters) => {
  return getIndexByOperation(state, getters, 'prev');
}

// 当前是否有歌曲在播放
export const hasCurrentSong = (state) => {
  return state.currentSong.id !== undefined && state.currentSong.id !== null
}

// 根据operation上一首或下一首索引
function getIndexByOperation(state, getters, operation) {
  let { playlist, playMode } = state
  let index = 0
  // 顺序
  if (playModeMap.sequence.code == playMode) {
    if (operation === 'next') {
      index = getters.currentIndex + 1
    }
    if (operation === 'prev') {
      index = getters.currentIndex - 1
    }
    index = index > playlist.length - 1 ? 0 : index
    index = index < 0 ? playlist.length - 1 : index
  }
  // 单曲
  if (playModeMap.loop.code == playMode) {
    index = getters.currentIndex
  }
  // 随机
  if (playModeMap.random.code == playMode) {
    index = getRandomIndex(state.playlist, getters.currentIndex)
  }
  return playlist[index]
}

function getRandomIndex(playlist, currentIndex) {
  // 防止无限循环
  if (playlist.length === 1) {
    return currentIndex
  }
  let index = Math.round(Math.random() * (playlist.length - 1))
  if (index === currentIndex) {
    index = getRandomIndex(playlist, currentIndex)
  }
  return index
}